<template>
  <Upload
    :action="jointPath(uploadUrl || defaultUploadUrl, data)"
    :multiple="multiple"
    :accept="accept"
    v-model:file-list="list"
    :headers="headers"
    :maxCount="maxCount"
    :beforeUpload="beforeUpload"
    @change="onUploadChange"
    :disabled="disabled"
    :list-type="listType"
    :showUploadList="showUploadList"
    @preview="onPreview"
    :data="data"
    :name="name || 'excelFileInfo'"
  >
    <slot name="content">
      <a-button v-if="!disabled">
        <upload-outlined />
        <span v-if="listType !== 'picture-card'">{{ title }}</span>
      </a-button>

      <span v-if="disabled && list.length < 1" style="color: #999; font-size: 14px">无</span>
    </slot>
  </Upload>
</template>
<script>
  import { Upload } from 'ant-design-vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '@/store/modules/user';
  import { useGlobSetting } from '@/hooks/setting';

  import { useMessage } from '@/hooks/web/useMessage';
  import {onMounted, reactive, ref, toRefs, watch} from 'vue';
  import { api as preview } from 'v-viewer';
  import { downloadByUrl } from '@/utils/file/download';
  import { appendArg, appendHeader } from '@/api/http';
  import { isHttpUrl } from '@/utils/is';
  import { jointPath } from '@/api/util.js';

  export default {
    name: 'AttachmentUpload',
    components: { Upload, UploadOutlined },
    props: {
      disabled: {
        type: Boolean,
        default: false,
      },
      changeAction: {
        type: String,
      },
      dataSource: {
        type: Array,
        default: () => [],
      },

      listType: {
        type: String,
      },

      showUploadList: {
        type: Object,
      },

      title: {
        type: String,
        default: '上传文件',
      },

      accept: {
        type: String,
        default: 'image/*',
      },

      multiple: {
        type: Boolean,
        default: false,
      },

      maxCount: {
        type: Number,
        default: 9999,
      },

      uploadUrl: {
        type: String,
      },

      contentType: {
        type: String,
      },

      name: {
        type: String,
      },
    },
    emits: ['changeLoading', 'update:dataSource'],

    setup(props, { emit }) {
      const { uploadUrl: defaultUploadUrl } = useGlobSetting();

      const userStore = useUserStore();
      const { createMessage } = useMessage();

      const state = reactive({
        defaultUploadUrl,
        data: { ...appendArg() },
        headers: {
          authorization: userStore.getToken,
          ...appendHeader(),
        },
      });

      const list = ref(props.dataSource);

      watch(
        () => props.dataSource,
        (value) => {
          list.value = value;
        },
      );
      watch(
        () => props.accept,
        (value,old) => {
          console.log(value, old)
        },
      );

      watch(list, (value) => {
        emit('update:dataSource', value);
      });
      onMounted(()=>{
        console.log(props.accept)
      })
      const beforeUpload = file => {
        const isPNG = props.accept.indexOf(file.type);

        console.log(isPNG,file.type)
        if (isPNG<0) {
          emit('changeLoading', false, 'error', file);
          createMessage.error(`${file.name} 文件格式不支持`);
          return Upload.LIST_IGNORE;
        } else {
          emit('changeLoading', true, 'start')
          return true;
        }
      };

      function onUploadChange({ file }) {
        const { response, status } = file;
        console.log(response,status)
        if (status === 'done') {
          const { result, soaStateBean } = response ?? {};
          const { isOk, msg } = soaStateBean ?? {};

          if (isOk === 0) {
            emit('changeLoading', false, msg, file);
            return createMessage.error(msg);
          }

          if (isHttpUrl(result)) {
            file.url = result;
          }

          emit('changeLoading', false, 'success', file);
        } else if (status === 'error') {
          emit('changeLoading', false, 'error', file);
          createMessage.error(response?.message || '文件上传失败');
        }
      }

      function onPreview(file) {
        if (props.listType === 'picture-card') {
          const index = list.value.findIndex((o) => o.url === file.url);

          preview({
            images: list.value.map((o) => o.url),
            options: {
              initialViewIndex: Math.max(index, 0),
              toggleOnDblclick: false,
            },
          });
        } else {
          downloadByUrl({ url: file.url });
        }
      }

      return {
        ...toRefs(state),
        beforeUpload,
        onUploadChange,
        onPreview,
        list,
        jointPath,
      };
    },
  };
</script>
